/*
 * @Description: 获取分页列表
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-10-14
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2023-11-01
 */

import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import type { Ref } from 'vue'
import { computed, readonly, ref } from 'vue'

import env from '@/env/index'

import { useLoading } from './useLoading'

/**
 * 获取分页列表
 * @param getList
 * @returns
 */
export const useQueryList = <T>(getList: (page: IPaginationRequest) => Promise<IPaginationResponse<T[]>['data']>) => {
  const pagination = { pageSize: env.PAGE_SIZE, page: 1 }
  const total = ref<number>(0)
  const records: Ref<T[]> = ref([])
  const empty = computed(() => fetch.firstLoaded.value && !fetch.loading.value && !records.value.length)
  const next = ref(true)

  const fetch = useLoading(async () => {
    const data = await getList(pagination)
    const { total: _total, current, size } = data ?? {}
    next.value = current * size < _total
    total.value = _total
    pagination.page == 1 && (records.value.length = 0)
    if (next.value) pagination.page++
    records.value = [...records.value, ...(data?.records ?? [])]
  })

  /** 页面触底加载下一页 */
  onReachBottom(async () => {
    if (fetch.loading.value || !next.value) return
    await fetch.trigger()
  })

  /** 页面下拉刷新 */
  onPullDownRefresh(async () => {
    records.value.length = 0
    pagination.page = 1
    await fetch.trigger()
    uni.stopPullDownRefresh()
  })

  return {
    total: readonly(total),
    next: readonly(next),
    empty: readonly(empty),
    loading: readonly(fetch.loading),
    records: readonly(records) as unknown as T[],
    queryList: async () => {
      records.value.length = 0
      pagination.page = 1
      return await fetch.trigger()
    },
  }
}
